﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;


namespace BasicallyNot.CodeTransformers.Handlers
{

	internal class EndBlock : IVisualHandler
	{

		void IVisualHandler.Handle( VisualHandlerEventArg arg )
		{
			int spanStart = arg.Line.Start + arg.SearchResult.MatchIndex;
			int spanEnd = spanStart + arg.Keyword.Value.Length;
			SnapshotSpan span = new SnapshotSpan( arg.Manager.View.TextSnapshot, Span.FromBounds( spanStart, spanEnd ) );
			Geometry g = arg.Manager.View.TextViewLines.GetMarkerGeometry( span );

			if ( g != null ) {
				GeometryDrawing drawing = new GeometryDrawing( arg.Manager.EditorBackground, null, g );
				drawing.Freeze();

				DrawingImage drawingImage = new DrawingImage( drawing );
				drawingImage.Freeze();

				Image coverImage = new Image();
				coverImage.Source = drawingImage;

				TextBlock curlyBracket = new TextBlock();
				curlyBracket.Text = "}";
				curlyBracket.Foreground = arg.CurlyBracketForeground;
				curlyBracket.FontFamily = arg.Manager.FontFamily;
				curlyBracket.FontSize = arg.Manager.FontSize;

				TextBlock keywordText = new TextBlock();
				keywordText.Text = arg.Keyword.Value;
				keywordText.Foreground = arg.KeywordForeground;
				keywordText.FontFamily = arg.Manager.FontFamily;
				keywordText.FontSize = arg.Manager.FontSize;
				keywordText.TextAlignment = TextAlignment.Right;
				keywordText.Width = g.Bounds.Width;

				// align the text with the top of the bounds of the text geometry
				Canvas.SetLeft( coverImage, g.Bounds.Left );
				Canvas.SetTop( coverImage, g.Bounds.Top );

				Canvas.SetLeft( curlyBracket, g.Bounds.Left );
				Canvas.SetTop( curlyBracket, g.Bounds.Top + 2 );

				Canvas.SetLeft( keywordText, g.Bounds.Left );
				Canvas.SetTop( keywordText, g.Bounds.Top + 2 );

				arg.Manager.Layer.AddAdornment( AdornmentPositioningBehavior.TextRelative, span, null, coverImage, null );
				arg.Manager.Layer.AddAdornment( AdornmentPositioningBehavior.TextRelative, span, null, curlyBracket, null );
				arg.Manager.Layer.AddAdornment( AdornmentPositioningBehavior.TextRelative, span, null, keywordText, null );
			}
		}

	}

}
